package com.example.common;

import com.example.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;


/**
 * jwt拦截器
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 从http请求的header中获取token
        var token = request.getHeader("Token");

        // 2. 开始执行认证 没有则直接返回
        //如果前端的请求头中有token并且后端Redis存储的token有效 则用户有权限操作
        if (token != null && redisTemplate.opsForValue().get(token) != null) {

            //重置token有效时间
            redisTemplate.expire(token,30, TimeUnit.MINUTES);

            // 获取 token 中的userId
//            String userId;
//            User user;
//            try {
//                userId = JWT.decode(token).getAudience().get(0);
//                // 根据token中的userid查询数据库
//                user = userService.findById(Integer.parseInt(userId));                                      //此处问题  若token失效 依旧可以查询到数据库的数据
//            } catch (Exception e) {
//                String errMsg = "token验证失败，请重新登录";
//                log.error(errMsg + ", token=" + token, e);
//                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                throw new CustomException(errMsg);
//            }
//            if (user == null) {
//                throw new CustomException("用户不存在，请重新登录");
//            }
//            try {
//                // 用户密码加签验证 token
//                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//                jwtVerifier.verify(token); // 验证token
//            } catch (JWTVerificationException e) {
//                throw new CustomException("token验证失败，请重新登录");
//            }

            return true;

        }
        else{
            //设置响应状态码 401表示未授权
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}